﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace TerminationCall.Core {
    public class LevelSaver {

        private BinaryWriter _binaryWriter;

        public void Save(string fileName, Level level) {

            _binaryWriter = new BinaryWriter(File.OpenWrite(fileName));
            
            _binaryWriter.Write(level.Layers.Count);

            foreach (Layer layer in level.Layers) {

                int horizontalFields = layer.Fields.GetLength(0);
                int verticalFields = layer.Fields.GetLength(1);

                _binaryWriter.Write(horizontalFields);
                _binaryWriter.Write(verticalFields);

                for (int x = 0; x < horizontalFields; x++) {
                    for (int y = 0; y < verticalFields; y++) {

                        Field field = layer.Fields[x, y];

                        Tile[] tiles = field.TileField.Tiles;

                        _binaryWriter.Write(tiles.Length);

                        foreach (Tile tile in tiles) {
                            _binaryWriter.Write(tile.TileSet.Name);
                            _binaryWriter.Write(tile.TileFields.ToString());
                            _binaryWriter.Write(tile.NumberX);
                            _binaryWriter.Write(tile.NumberY);
                        }
                    }
                }

            }



            _binaryWriter.Close();

        }
    }
}
